package com.example.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HtmlUtil;
import com.example.entity.Account;
import com.example.entity.Comment;
import com.example.entity.Written;
import com.example.mapper.CommentMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentService {

    @Resource
    CommentMapper commentMapper;

    // 创建评论
    public void createComment(Comment comment) {
        comment.setTime(DateUtil.now());
        commentMapper.insert(comment);
    }

    // 构建树形结构（递归实现）
    public List<Comment> getCommentTree(Integer writtenId) {
        return commentMapper.selectByWrittenId(writtenId);
    }

    private List<Comment> buildTree(List<Comment> comments) {
        return comments.stream()
                .peek(comment -> {
                    List<Comment> children = commentMapper.selectChildren(comment.getId());
                    if (!children.isEmpty()) {
                        comment.setChildren(buildTree(children));
                    }
                })
                .collect(Collectors.toList());
    }

    public List<Comment> selectAll(Comment comment) {
        List<Comment> list = commentMapper.selectAll(comment);
        return list;
    }

    public List<Comment> selectByUserId(Integer userId) {
        List<Comment> comments = commentMapper.selectByUserId(userId);
        return comments;
    }

    public void deleteById(Integer id) {
        commentMapper.deleteById(id);
    }

    public PageInfo<Comment> selectPage(Integer pageNum, Integer pageSize, Comment comment) {
        Account currentUser = TokenUtils.getCurrentUser();
        if ("USER".equals(currentUser.getRole())){
            comment.setUserId(currentUser.getId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> list = commentMapper.selectAll(comment);
        return PageInfo.of(list);
    }
}